import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/pages/transaction_flow/item/transaction_flow_item.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';
import 'package:nyh_motorcade_app/widgets/custom_app_bar.dart';
import 'package:nyh_motorcade_app/widgets/custom_popup_menu_item.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/default_empty_widget.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/default_error_widget.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/default_fail_widget.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/default_loading_widget.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:nyh_motorcade_app/widgets/text_button_with_icon.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'transaction_flow_controller.dart';

class TransactionFlowPage extends StatelessWidget {
  final controller = Get.put(TransactionFlowController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.color_background,
      appBar: CustomAppBar(
        context: context,
        title: "交易流水",
        actions: [
          Container(
            width: 205.w,
            margin: EdgeInsets.only(left: 5.w, top: 6.w, right: 16.w, bottom: 6.w),
            child: TextButtonWithIcon(
              onPressed: () {
                controller.goToSearchTransactionFlowPage();
              },
              icon: Image.asset("images/ic_search_gray.png"),
              label: Text(
                "请输入车牌号/司机姓名",
                style: TextStyle(color: Colours.color_cfcfd5, fontSize: 14.sp),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              textIconPadding: 10.w,
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colours.color_background),
                shape: MaterialStateProperty.all(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(28.w),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
      body: GetBuilder<TransactionFlowController>(
        builder: (controller) {
          return SmartRefresher(
            controller: controller.refreshController,
            enablePullDown: true,
            enablePullUp: true,
            onRefresh: controller.onRefresh,
            onLoading: controller.onLoading,
            child: CustomScrollView(
              slivers: [
                buildHeaderWidget(),
                buildStickyHeaderWidget(),
                buildContentWidget(),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget buildHeaderWidget() {
    if (controller.queryType.isNotEmpty) {
      return SliverToBoxAdapter(
        child: Container(),
      );
    }
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.only(left: 16.w, top: 12.w, right: 16.w),
        decoration: BoxDecoration(
          color: Colours.color_white,
          borderRadius: BorderRadius.circular(10.w),
          boxShadow: [
            BoxShadow(
              color: Colours.color_0f112e_95,
              offset: Offset(0.0, 2.w),
              blurRadius: 5.w,
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10.w),
          child: Material(
            child: InkWell(
              onTap: () {
                controller.changeCompany();
              },
              child: Padding(
                padding: EdgeInsets.symmetric(
                  vertical: 13.w,
                  horizontal: 16.w,
                ),
                child: Row(
                  children: [
                    Image.asset(
                      "images/ic_company_circle.png",
                      fit: BoxFit.cover,
                      height: 42.w,
                      width: 42.w,
                    ),
                    SizedBox(
                      width: 16.w,
                    ),
                    Expanded(
                      child: Text(
                        controller.companyName,
                        style: TextStyle(
                          color: Colours.color_text_theme,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    SizedBox(
                      width: 5.w,
                    ),
                    Visibility(
                      visible: controller.companyList.length > 1,
                      child: Image.asset("images/ic_arrow_right_gray.png"),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget buildStickyHeaderWidget() {
    return SliverToBoxAdapter(
      child: Container(
        height: 40.w,
        padding: EdgeInsets.only(left: 8.w, right: 16.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            TextButtonWithIcon(
              onPressed: () {
                showDateMenu();
              },
              icon: Image.asset(controller.showDateTypeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
              label: Text(
                controller.selectDateName,
                style: TextStyle(
                  color: Colours.color_text_theme,
                  fontSize: 14.sp,
                ),
              ),
              textIconPadding: 5.w,
              iconTextAlignment: IconTextAlignment.iconRightTextLeft,
            ),
            Row(
              children: [
                Text(
                  controller.orderAmount == 0.0 ? "" : "累计${FormatUtils.formatMoney(controller.orderAmount, unit: "元")}",
                  style: TextStyle(
                    color: Colours.color_b7b7c0,
                    fontSize: 12.sp,
                  ),
                ),
                Container(
                  width: 1.w,
                  height: 10.w,
                  color: (controller.orderAmount == 0.0 && controller.orderCount == 0) ? Colours.color_transparent : Colours.color_e7e7ea,
                  margin: EdgeInsets.symmetric(horizontal: 8.w),
                ),
                Text(
                  controller.orderCount == 0 ? "" : "${controller.orderCount}笔",
                  style: TextStyle(
                    color: Colours.color_b7b7c0,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void showDateMenu() {
    if (controller.dateTypeList.isEmpty) {
      return;
    }
    controller.showDateTypeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(16.w, ScreenUtil().statusBarHeight + 56 + (controller.queryType.isNotEmpty ? 40.w : 120.w), ScreenUtil().screenWidth, 0.w),
      items: controller.dateTypeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.dateTypeList[e].name)).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectDateType(value);
    });
  }

  // Widget buildStickyHeaderWidget() {
  //   return SliverPersistentHeader(
  //     pinned: true,
  //     floating: false,
  //     delegate: StickyHeaderDelegate(
  //       minHeight: 40.w,
  //       maxHeight: 40.w,
  //       child: Container(
  //         width: double.infinity,
  //         height: double.infinity,
  //         margin: EdgeInsets.symmetric(horizontal: 16.w),
  //         child: Row(
  //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //           children: [
  //             GetBuilder<TransactionFlowController>(
  //               builder: (controller) {
  //                 return DropdownBelow(
  //                   itemWidth: 120.w,
  //                   itemTextstyle: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
  //                   boxTextstyle: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
  //                   boxWidth: 61.w,
  //                   boxHeight: 40.w,
  //                   icon: Image.asset("images/ic_arrow_down.png"),
  //                   hint: Text("近一周"),
  //                   value: controller.selectDropdownIndex,
  //                   items: controller.buildDropdownMenuItem(),
  //                   onChanged: (value) {
  //                     controller.onChangeDropdown(value);
  //                   },
  //                 );
  //               },
  //             ),
  //             Row(
  //               children: [
  //                 Text(
  //                   controller.orderAmount == 0.0 ? "" : "累计${FormatUtils.formatMoney(controller.orderAmount, unit: "元")}",
  //                   style: TextStyle(
  //                     color: Colours.color_b7b7c0,
  //                     fontSize: 12.sp,
  //                   ),
  //                 ),
  //                 Container(
  //                   width: 1.w,
  //                   height: 12.w,
  //                   color: (controller.orderAmount == 0.0 && controller.orderCount == 0) ? Colours.color_transparent : Colours.color_e7e7ea,
  //                   margin: EdgeInsets.symmetric(horizontal: 8.w),
  //                 ),
  //                 Text(
  //                   controller.orderCount == 0 ? "" : "${controller.orderCount}笔",
  //                   style: TextStyle(
  //                     color: Colours.color_b7b7c0,
  //                     fontSize: 12.sp,
  //                   ),
  //                 ),
  //               ],
  //             ),
  //           ],
  //         ),
  //       ),
  //     ),
  //   );
  // }

  Widget buildContentWidget() {
    return controller.transactionFlowList.isNotEmpty
        ? SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return TransactionFlowItem(controller.transactionFlowList[index]);
              },
              childCount: controller.transactionFlowList.length,
            ),
          )
        : SliverFillRemaining(
            child: getMultiStateWidget(),
          );
  }

  Widget getMultiStateWidget() {
    switch (controller.multiState) {
      case MultiState.loading:
        return DefaultLoadingWidget();
      case MultiState.empty:
        return DefaultEmptyWidget();
      case MultiState.fail:
        return DefaultFailWidget();
      case MultiState.error:
        return DefaultErrorWidget(
          onRetry: () {
            controller.onRetry();
          },
        );
      default:
        return Container();
    }
  }
}

class StickyHeaderDelegate extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double minHeight;
  final double maxHeight;

  StickyHeaderDelegate({required this.child, required this.minHeight, required this.maxHeight});

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return this.child;
  }

  @override
  double get maxExtent => maxHeight;

  @override
  double get minExtent => minHeight;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
